// wechat oauth request
(function() {
  var OAuth, appId, appSecret, config, getToken, log4js, logger, oauthApi, redisClient, saveToken;

  config = require('config');

  log4js = require('log4js');

  redisClient = require('../utils/redis');

  OAuth = require('wechat-oauth');

  appId = config.wechat.appid;

  appSecret = config.wechat.appsecret;

  logger = log4js.getLogger('oauthApi');


  /*
   * 获取全局oauth token的方法
   * 尝试从redis中获取token
   */

  getToken = function(openid, callback) {
    return redisClient.get("wx_mp_oauth_access_token_" + openid, function(err, reply) {
      if (err) {
        return callback(err);
      } else {
        return callback(null, reply);
      }
    });
  };


  /*
   * 保存token到redis缓存中
   */

  saveToken = function(openid, token, callback) {
    redisClient.set("wx_mp_oauth_access_token_" + openid, token);
    redisClient.expire("wx_mp_oauth_access_token_" + openid, 7000);
    return callback(null);
  };

  oauthApi = new OAuth(appId, appSecret, getToken, saveToken);

  module.exports = oauthApi;

}).call(this);
